package com.party.web.web.interceptor;

import com.party.common.constant.Constant;
import com.party.common.redis.StringJedis;
import com.party.common.utils.StringUtils;
import com.party.core.model.member.MemberGroup;
import com.party.core.model.member.ThirdMember;
import com.party.core.service.member.IThirdMemberService;
import com.party.web.biz.system.member.MemberGroupBizService;
import com.party.web.utils.RealmUtils;
import org.apache.shiro.session.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedWriter;
import java.io.OutputStreamWriter;
import java.lang.reflect.Method;
import java.util.List;

/**
 * 登陆拦截器
 * party
 * Created by wei.li
 * on 2016/8/30 0030.
 */
@Component(value = "loginInterceptor")
public class LoginInterceptor implements HandlerInterceptor {

    /**
     * 登陆URL
     */
    private static String LOGIN_URL = "/pLogin.do";
    /**
     * 第三方用户登录URL
     */
    private static String THIRD_LOGIN_URL = "/thirdLogin.do";
    /**
     * 没有权限URL
     */
    private static String NO_AUTHORIZATION_URL = "/user/login/noAuthorization.do";

    private static String[] openURL = new String[]{
            "/web/user/login/logout.do", "/web/piccloud/getSign.do", "/web/member/piccloud/getSign.do", "/web/fileupload/uploadCIImage.do",
            "/web/activity/activity/getDetailQrCode.do", "/web/file/img/api/list.do", "/web/file/img/api/save.do",
            "/web/cos/v4/api/getConfig.do", "/web/cos/v4/api/getAppSign.do", "/web/cos/v4/api/getAppSignOnce.do",
            "/web/file/img/selImg.do", "/web/file/video/selVideo.do", "/web/file/video/api/list.do", "/web/file/video/api/save.do",
            "/web/file/video/api/updatePoster.do", "/web/file/img/photo/uploadImg.do", "/web/photo/album/addPic.do", "/web/photo/album/third/tags.do",
            "/web/photo/album/third/photo/uploadImg.do", "/web/photo/album/third/addPic.do", "/web/photo/album/third/list.do"
    };

    private static String openUrl = StringUtils.join(openURL, ",");

    @Autowired
    private IThirdMemberService thirdMemberService;
    @Autowired
    private StringJedis stringJedis;
    @Autowired
    private MemberGroupBizService memberGroupBizService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String contextPath = request.getContextPath();
        //请求链接
        String requestURI = request.getRequestURI();
        //请求参数
        String requestParam = request.getQueryString();
        Session session = RealmUtils.getSession();

        MemberGroup member = (MemberGroup) session.getAttribute(Constant.CURRENT_USER_KEY);
        if (null != member) {
            // 第三方用户
            if (openUrl.indexOf(requestURI) == -1 && session.getAttribute(Constant.THIRD_USER_KEY) != null) {
                ThirdMember thirdMember = (ThirdMember) session.getAttribute(Constant.THIRD_USER_KEY);
                ThirdMember newThirdMember = thirdMemberService.get(thirdMember.getId());
                session.setAttribute(Constant.THIRD_USER_KEY, newThirdMember);
                String uri = newThirdMember.getUri();
                String alias = newThirdMember.getAlias();
                if (requestURI.indexOf(alias) == -1) { // 别名有表示是一起的，访问其他链接
                    if (requestURI.indexOf("/activity/activity/third/") != -1) {
                        response.sendRedirect(newThirdMember.getUri());
                    } else {
                        response.sendRedirect(contextPath + NO_AUTHORIZATION_URL);
                    }
                    return false;
                } else if (requestURI.equals(uri.substring(0, uri.indexOf(".do") + 3)) && uri.indexOf(requestParam) == -1) { // 访问当前链接，参数不对
                    response.sendRedirect(contextPath + NO_AUTHORIZATION_URL);
                    return false;
                }
            }
        }
        //如果没有用户登陆
        if (null == member) {
            // 检查当前链接是否为第三方用户访问的链接
            String thirdMemberList = stringJedis.getValue("thirdMemberList");
            if (StringUtils.isEmpty(thirdMemberList)) {
                List<String> uriAll = thirdMemberService.allURI();
                thirdMemberList = uriAll.toString();
                stringJedis.setValue("thirdMemberList", thirdMemberList);
            }
            if (thirdMemberList.indexOf(requestURI) != -1) {
                response.sendRedirect(contextPath + THIRD_LOGIN_URL);
            } else {
                if (handler instanceof HandlerMethod) {
                    HandlerMethod handlerMethod = (HandlerMethod) handler;
                    Method method = handlerMethod.getMethod();
                    ResponseBody methodAnnotation = method.getAnnotation(ResponseBody.class);
                    if (null == methodAnnotation) {
                        response.sendRedirect(contextPath + LOGIN_URL);
                    } else {
                        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
                        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(response.getOutputStream()));
                        writer.write("session timeout");
                        writer.close();
                    }
                } else {
                    if (requestURI.indexOf("/activity/activity/third/") != -1) {
                        ThirdMember thirdMember = (ThirdMember) session.getAttribute(Constant.THIRD_USER_KEY);
                        if (thirdMember == null) {
                            response.sendRedirect(contextPath + THIRD_LOGIN_URL);
                        }
                    }
                    else {
                        response.sendRedirect(contextPath + LOGIN_URL);
                    }
                }
            }
            return false;
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
